C# performance of static string[] contains() (slooooow) vs. == operator

Posted by Andrew White on Stack Overflow See other posts from Stack Overflow or by Andrew White
Published on 2010-05-20T22:30:04Z Indexed on 2010/05/20 23:00 UTC
Read the original article Hit count: 153

Filed under:

Hiya,

Just a quick query: I had a piece of code which compared a string against a long list of values, e.g.

if(str == "string1" || str = "string2" || str == "string3" || str = "string4".
     DoSomething();

And the interest of code clarity and maintainability I changed it to

public static string[] strValues = { "String1", "String2", "String3", "String4"};
...
if(strValues.Contains(str)
    DoSomething();

Only to find the code execution time went from 2.5secs to 6.8secs (executed ca. 200,000 times).
I certainly understand a slight performance trade off, but 300%?
Anyway I could define the static strings differently to enhance performance?
Cheers.

© Stack Overflow or respective owner

Related posts about c#